package com.chenwenxuan.sync;

import org.apache.log4j.Logger;
import org.hsqldb.server.Server;
import org.hsqldb.server.ServerConstants;


public class HSQLLauncher {

	private Logger logger = Logger.getLogger(HSQLLauncher.class);
	
	private static Server dbserver;
	
	private String address;
	private int port;
	private String dbName;
	private String dblocation;
	private boolean silent;
	private boolean trace;
	private boolean tls;

	public int start() {
		logger.info("start hsqldb: address=" + address + " port=" + port + " dbName=" + dbName + " dblocation=" + dblocation);
		dbserver = new Server();

		dbserver.setNoSystemExit(true);
		dbserver.setTls(tls);
		dbserver.setTrace(trace);
		dbserver.setSilent(silent);
		dbserver.setDatabasePath(0, dblocation);
		dbserver.setDatabaseName(0, dbName);
		dbserver.setPort(port);
		dbserver.setAddress(address);
		int result = dbserver.start();
		logger.info("hsqldb started with result code: " + result);
		return result;

	}

	public static Server getHSQLServerInstance() {
		return dbserver;
	}

	public int stop() {
		logger.info("stopping hsqldb...");
		dbserver.stop();
		while (dbserver.getState() == ServerConstants.SERVER_STATE_CLOSING) {
			try {
				Thread.sleep(100);
			} catch (InterruptedException e) {
			}
		}
		logger.info("hsqldb stopped...");
		return 0;
	}
	
	public void waitUtilStop() {
		waitState(ServerConstants.SERVER_STATE_SHUTDOWN);
	}
	
	protected void waitState(int state) {
		while (dbserver.getState() != state) {
			try {
				Thread.sleep(100);
			} catch (InterruptedException e) {
			}
		}
	}

	public static Server getDbserver() {
		return dbserver;
	}

	public static void setDbserver(Server dbserver) {
		HSQLLauncher.dbserver = dbserver;
	}

	public String getAddress() {
		return address;
	}

	public void setAddress(String address) {
		this.address = address;
	}

	public int getPort() {
		return port;
	}

	public void setPort(int port) {
		this.port = port;
	}

	public String getDbName() {
		return dbName;
	}

	public void setDbName(String dbName) {
		this.dbName = dbName;
	}

	public String getDblocation() {
		return dblocation;
	}

	public void setDblocation(String dblocation) {
		this.dblocation = dblocation;
	}

	public boolean isSilent() {
		return silent;
	}

	public void setSilent(boolean silent) {
		this.silent = silent;
	}

	public boolean isTrace() {
		return trace;
	}

	public void setTrace(boolean trace) {
		this.trace = trace;
	}

	public boolean isTls() {
		return tls;
	}

	public void setTls(boolean tls) {
		this.tls = tls;
	}
	
	

}
